package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"yk1-assistant/models"
)

func ListUserRole(c *gin.Context) {
	var role []models.Role
	uid := c.Query("uid")
	//SELECT
	//*
	//	FROM
	//roles
	//LEFT JOIN user_roles on user_roles.rid=roles.id
	//WHERE user_roles.uid=1
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": role,
	})
	return
}
func AddRoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{

		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListRoleNode(c *gin.Context) {
	var node []models.Node
	rid := c.Query("rid")
	//SELECT
	//*
	//	FROM
	//roles
	//LEFT JOIN user_roles on user_roles.rid=roles.id
	//WHERE user_roles.uid=1
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes on role_nodes.nid=nodes.id").
		Where("role_nodes.rid=?", rid).Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": node,
	})
	return
}
func AddUserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := models.UserRole{

		Uid: uid,
		Rid: rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
